package com.jeeplus.modules.api.utils;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class ZhongTaiUtil {
	private static final String APPID = "A0F4B48557932BC1A0E75BAD19187EDA";
	private static final String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpJXtyIYuAWFiS/ueO8GcdLsWiubHZnAvVNjFRfdIzRYBGtP7Tz1OIJOXgjwPTIu2QWB93CvxSSDgRWFB0DO5R5UdWNdrCmaXPGckXDkg+ezcpsHr0DaktGTtMWn68+2Rvc7ufozygNw7glGwJjCpPISKrIm6yqFgnAeE6ulyp8wIDAQAB";
	
	/**
	 * 获取请求地址
	 * @param authInfo 认证信息
	 * @param type 1机票 2火车票 3酒店
	 * @return
	 */
	public static String getUrl(String authInfo, String type){
		if ("1".equals(type)) {
			return "https://flight.bflvx.com?" + APPID + "&authinfo=" + authInfo;
		}
		if ("2".equals(type)) {
			return "https://h5.ztlvx.com/hotel/auth/third_auth/" + APPID + "?authinfo=" + authInfo;
		}
		return "https://h5.ztlvx.com/train/auth/third_auth/" + APPID + "?authinfo=" + authInfo;
	}
	/**
	 * 获取认证信息
	 * @param tel 手机号
	 * @return
	 */
	public static String getAuthInfo(String tel){
		return getAuthInfo(tel, "WEB_M");
	}
	/**
	 * 获取认证信息
	 * @param tel 手机号
	 * @param chanel 渠道
	 * @return
	 */
	public static String getAuthInfo(String tel, String chanel){
		long timestamp = System.currentTimeMillis();//时间戳
		
		JSONObject json = new JSONObject();
		json.put("tel", tel);//手机号
		json.put("timestamp", timestamp);//时间戳
		json.put("chanel", chanel);//渠道
		String sign = getMd5Value(tel + timestamp + APPID + publicKeyStr);
		json.put("sign", sign);//签名
		
		System.out.println("认证信息："+json.toJSONString());
		
		String encryptStr = "";
		try {
			byte[] encryByte = encrypt(json.toJSONString(), publicKeyStr);
			encryptStr = Base64.getUrlEncoder().encodeToString(encryByte);
		} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException
				| BadPaddingException | IllegalBlockSizeException e) {
			e.printStackTrace();
		}
		System.out.println("加密结果："+encryptStr);
		return encryptStr;
	}
	
	/**
     * 公钥加密
     * @return 返回加密后的字符串
     */
    private static byte[] encrypt(String str, String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        //base64编码的公钥
        byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
    }
	
    private static String getMd5Value(String sSecret) {
        try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(sSecret.getBytes());
            StringBuffer buf = new StringBuffer();
            byte[] b = bmd5.digest();

            for(int offset = 0; offset < b.length; ++offset) {
                int i = b[offset];
                if (i < 0) {
                    i += 256;
                }

                if (i < 16) {
                    buf.append("0");
                }

                buf.append(Integer.toHexString(i));
            }

            return buf.toString();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
            return "";
        }
    }
}
